import { connect } from 'react-redux'
import { Image, Text, View } from "@tarojs/components";
import React, { Component, Dispatch } from 'react'
import { AtActivityIndicator, AtButton, AtMessage, AtRadio } from "taro-ui";
import cabinet from "../../images/battery.png";
import './Cabinet.scss'
import { checkGoods } from '../../actions/goods';
import { checkMenus } from '../../actions/menus'
import { createOrder, getUserWallet, setCabinetId } from '../../actions/global';
import { payBattery } from '../../actions/pay'
import { WXRequest } from '../../utils/WXRequest';
import { URL_MY_WALLET } from '../../constants/SystemConstants';
import { getCurrentInstance } from '@tarojs/taro';

class Cabinet extends Component{

  state = {
    value: 'wallet',
    myWalletCharingNum: 0,
    payWayList: [],
    cabinetId: '0'
  }

  componentDidMount () {}

  componentDidShow () {
    this.setState({
      cabinetId: getCurrentInstance().router?.params.eid?.toString()
    }, () => {
      // this.props.setCabinetId()
      WXRequest(URL_MY_WALLET, 'GET', {}).then(res => {
        const payWayList = [
          // 换电买商品，换电次数ID：-1
          // 租电买套餐，租电套餐ID：-1
          { label: '钱包支付', value: 'wallet', desc: '爱骑钱包支付，剩余（'+ this.state.myWalletCharingNum +'）次' },
          { label: '微信支付', value: 'wechatpay', desc: '微信支付' },
          { label: '租电押金套餐', value: 'zudian', desc: '新用户租电押金套餐', disabled: false }
        ]
        res.data.forEach((item, index) => {
          console.log(item)
          if (item.commodity.id === -1) {
            if (item.available <= 0) {
              payWayList[0].disabled = true
              this.setState({
                myWalletCharingNum: item.available,
                value: 'wechatpay'
              })
            } else {
              payWayList[0].desc = '爱骑钱包支付，剩余（'+ item.available +'）次'
              console.log('剩余大于0', item.available)
              this.setState({
                myWalletCharingNum: item.available,
                value: 'wallet'
              })
            }
          }
          if (item.commodity.id === -2 || item.commodity.id === -3) {
            payWayList[2].disabled = true
          }
        })
        this.setState({
          payWayList: payWayList
        })
      }).catch(e => {
        console.error(e)
      })
      this.handleChange(this.state.value)
      this.props.getUserWallet()
    })
  }

  componentDidHide () {}

  componentDidCatchError () {}

  handleChange (value) {
    this.setState({
      value: value
    },() => {
      if (value === 'wechatpay' || value === 'wallet') {
        this.props.getGoods(-1)
        this.setState({
          goodsDetail: this.props.goods
        })
        return
      }
      this.props.getMenus(-1)
      this.setState({
        goodsDetail: this.props.menu
      })
      console.log(this.state.value)
      
    })
  }

  toCreateOrder () {
    let orderData = {};
    if (this.state.value === 'wallet' || this.state.value === 'wechatpay') {
      orderData = {
        orderItems: [
          {
            commodityId: -1,
            count: 1
          }
        ],
        userId: parseInt(this.props.user.userId),
        summary: '换电次数'  
      }
    }
    this.props.createOrder(orderData)
  }

  toPay () {
    let orderData = {}
    let type = 'wechat'
    if (this.state.value === 'zudian') {
      type = 'zudian'
      orderData = {
        menuIds: [
          -1
        ],
        userId: parseInt(this.props.user.userId),
        summary: '换电次数'
      }
    } else {
      orderData = {
        orderItems: [
          {
            commodityId: -1,
            count: 1
          }
        ],
        userId: parseInt(this.props.user.userId),
        summary: '换电次数'
      }
      if (this.state.value === 'wallet') type = 'wallet'
      if (this.state.value === 'wechatpay') type = 'wechatpay'
    }
    this.props.toPay(this.state.cabinetId, orderData, type)
  }

  render () {
    const mask = () => {
      if (this.props.pending) {
        return (
          <View style='position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99; background: rgba(0, 0, 0, 0.2)'>
            <AtActivityIndicator mode='center' size={64}></AtActivityIndicator>
          </View>
        )
      }
    }
    let myWalletCharingNum = 0;
    // this.props.userWallet.forEach(item => {
    //   if (item.commodity.id === -1) {
    //     myWalletCharingNum = item.available
    //   }
    // })
    return (
      <View>
        <AtMessage />
        {mask()}
        <View style='width: 100%; text-align: center;'>
          电柜标识：{this.state.cabinetId}
        </View>
        <View className='cabinet-image-box'>
          <Image mode='aspectFit' src={cabinet} style='height: 100%; width: 100%' />
        </View>
        <View className='cabinet-pay-price'>
          <Text>
            ¥{ (this.props.goods.price || this.props.menu.price) / 100 } / 次
          </Text>
        </View>
        <View className='cabinet-pay-box'>
          <AtRadio
            options={this.state.payWayList}
            value={this.state.value}
            onClick={this.handleChange.bind(this)}
          />
        </View>
        <View className='cabinet-pay-footer'>
          <AtButton type='primary' onClick={this.toPay.bind(this)}>
            立即支付
          </AtButton>
        </View>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    pending: state.goods.pending,
    goods: state.goods.goods,
    cabinetId: state.global.cabinetId,
    userWallet: state.global.userWallet,
    user: state.user,
    menu: state.menus.menu
  }
}

const mapDispatchToProps = (dispatch) => ({
  getGoods(id) {
    dispatch(checkGoods(id))
  },
  setCabinetId (id) {
    dispatch(setCabinetId(id))
  },
  getMenus(id) {
    dispatch(checkMenus(id))
  },
  getUserWallet() {
    dispatch(getUserWallet())
  },
  createOrder(orderData) {
    dispatch(createOrder(orderData))
  },
  toPay(eid, orderData, type) {
    dispatch(payBattery(eid, orderData, type))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(Cabinet)